import React, { useState, useEffect } from 'react';;
import {
    EditableProTable,
    ProForm,
    ProFormText, ProTable,
} from '@ant-design/pro-components';
import {Modal, Space, Upload} from "antd";
import Decimal from "decimal.js";
import TheButton from "@/components/TheButton/index.jsx";
import TheImage from "@/components/TheImage/index.jsx";
import {apiGetUserList,apiImportUser} from "@/api/couponManagement/timeTask.jsx";
import Json2Excel from "@/utils/Json2Excel.js";
const CouponList = (props) => {
    const selectKeys = props.value.map((item) => item.memberId);
    const [editableKeys, setEditableRowKeys] = useState(() =>
        props.value.map((item) => item.memberId),
    );
    const [dataSource, setDataSource] = useState(props.value || []);
    const [selectedRows, setSelectedRows] = useState(props.value);
    const [modalOpen, setModalOpen] = useState(false);
    const columns = [
        {
            title: '用户id',
            dataIndex: 'memberId',
            key: 'memberId',
            editable: false,
        },
        {
            title: "用户昵称",
            dataIndex: "wxNickName",
            key: "wxNickName",
            hideInTable: true
        },
        {
            title: '头像',
            dataIndex: 'memberAvatar',
            key: 'memberAvatar',
            editable: false,
            hideInSearch: true,
            render: (text) => {
                return <TheImage src={[text]} width={80} height={80}></TheImage>
            }
        },
        {
            title: '昵称',
            dataIndex: 'nickName',
            key: 'nickName',
            editable: false,
            hideInSearch: true
        },
        {
            title: '手机号',
            dataIndex: 'memberMobile',
            key: 'memberMobile',
            hideInSearch: true,
            editable: false
        },
        {
            title: '身份',
            dataIndex: 'memberType',
            key: 'memberType',
            editable: false,
            hideInSearch: true,
            valueEnum: {
                'R': { text: '注册会员' },
                'P': { text: '正式会员' },
                'S': { text: '商户会员' },
            },
        },
        {
            title: '状态',
            dataIndex: 'memberStatus',
            key: 'memberStatus',
            editable: false,
            hideInSearch: true,
            valueEnum: {
                'Y': { text: '正常' },
                'N': { text: '冻结' },
            },
        },
        {
            title: '注册时间',
            dataIndex: 'memberCreatedTime',
            key: 'memberCreatedTime',
            valueType: 'dateTime',
            editable: false,
            hideInSearch: true,
            width: 250
        },

    ]
    useEffect(()=>{
      if(props.mode === "edit") {
        setSelectedRows(props.value)
      }
    },[])
    // 导入
    const uploadProps = {
        name: 'file',
        maxCount: 1,
        showUploadList: false,
        onChange: (info) => {
            if (info.file.status === 'done') {
                message.success('上传成功');
            }
            if (info.file.status === 'error') {
                message.error('上传失败');
            }
        },
        customRequest: (option) => {
            // console.log("option:",option);
            let params = {
                file: option.file,
            }
            apiImportUser(params).then(res=>{
                // console.log(res)
                setDataSource(res.data)
            })
        }
    }
    // 下载模板
    const downloadDemo = () => {
        const option = {
            fileName: '用户表',
            header: [
                {
                    prop: 'memberId',
                    title: '用户ID',
                    valueType: 'n',
                },
                {
                    prop: 'memberMobile',
                    title: '用户手机号',
                    valueType: 'n',
                },
            ],
            dataSource: []
        }
        Json2Excel(option)
    }
    let tableProps = {}
    if (props.mode === 'view'){
        tableProps = {
            toolBarRender: false
        }
    }
    else {
        tableProps = {
            toolBarRender: (action) => {
                return action.toolBarRender
            }
        }
    }
    return <>
        <EditableProTable
            rowKey="memberId"
            bordered={true}
            cardBordered={true}
            scroll={{y: '500px'}}
            {...tableProps}
            headerTitle={
                <Space>
                    <TheButton
                        key="new"
                        onClick={() => {
                            setModalOpen(true)
                        }}
                    >
                        选择用户
                    </TheButton>
                    <Upload {...uploadProps}>
                        <TheButton
                            key="into"
                        >
                            批量导入
                        </TheButton>
                    </Upload>
                    <TheButton
                        key="down"
                        onClick={() => {
                            downloadDemo()
                        }}
                    >
                        下载导入文件模板
                    </TheButton>
                </Space>
            }
            columns={[...columns,{
                title: '操作',
                valueType: 'option',
                width: 250,
                fixed: "right",
                hideInTable: props.mode === 'view',
                render: () => {
                    return null;
                },
            }]}
            recordCreatorProps={false}
            value={dataSource}
            controlled={true}
            onChange={props.onValuesChange}
            editable={{
                type: 'multiple',
                editableKeys,
                onChange: setEditableRowKeys,
                actionRender: (row, _, dom) => {
                    return <Space style={{margin:"0 auto"}}>{[dom.delete]}</Space>;
                },
                onValuesChange: (record, recordList) => {
                    setDataSource(recordList);
                },
            }}
            pagination={{
                defaultPageSize: 5
            }}
        />
        <Modal
            title={'选择用户'}
            width={'80%'}
            open={modalOpen}
            destroyOnClose={true}
            onOk={() => {
              // console.log(selectedRows);
              if(selectedRows.length) {
                setDataSource(selectedRows)
                setEditableRowKeys(selectedRows.map((item) => item.memberId))
              }
              props.onValuesChange(selectedRows)
              setModalOpen(false)
            }}
            onCancel={() => setModalOpen(false)}
        >
            <ProTable
                bordered={true}
                options={false}
                scroll={{x: "max-content", y: '57vh'}}
                rowKey={(record) => record.memberId}
                columns={columns}
                params={{
                    memberStatus:'Y'
                }}
                request={async (params, sort, filter) => {
                    // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
                    // 如果需要转化参数可以在这里进行修改
                    const res = await apiGetUserList({
                        pageNo: params.current,
                        pageSize: params.pageSize,
                        ...params
                    });
                    return {
                        data: res.data,
                        // success 请返回 true，
                        // 不然 table 会停止解析数据，即使有数据
                        success: res.code === 0,
                        // 不传会使用 data 的长度，如果是分页一定要传
                        total: res.totalCount,
                    };
                }}
                pagination={{
                    defaultPageSize: 10
                }}
                rowSelection={{
                    defaultSelectedRowKeys: selectKeys,
                    preserveSelectedRowKeys: true,
                    onChange: (keys, rows) => {
                      setSelectedRows((prev) => {
                          let arr = []
                          rows.forEach((item,index)=>{
                              if (item === undefined){
                                  arr.push(prev.find(v=>v.memberId === keys[index]))
                              }
                              else{
                                  arr.push(item)
                              }
                          })
                          return arr;
                      });
                  }
                }}
                search={{
                    optionRender: (searchConfig,formProps,dom)=>{
                        return dom.reverse()
                    }
                }}
            />
        </Modal>
    </>
};

export default CouponList;
